package com.b2b2c.store.single.logic;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import com.b2b2c.store.single.entity.StoreAuthGroup;
import com.b2b2c.store.single.entity.StoreAuthMenu;
import com.b2b2c.store.single.mapper.StoreAuthMenuMapper;
import com.b2b2c.store.single.service.IStoreAuthMenuService;
import com.b2b2c.until.MD5;


public class StoreAuthMenuLogic extends AbstractLogic<StoreAuthMenu, StoreAuthGroup> implements IStoreAuthMenuService<StoreAuthMenu>{

	public StoreAuthMenuLogic(Map<String, String> args) {
		super(args);
		// TODO Auto-generated constructor stub
	}
	
	public StoreAuthMenuLogic(HttpServletRequest req) {
		super(req);
		// TODO Auto-generated constructor stub
	}
	
	public StoreAuthMenuLogic(List<StoreAuthGroup> data, HttpServletRequest req) {
		// TODO Auto-generated constructor stub
		super(data, req);
	}
	
	
	public List<StoreAuthMenu> getAuthGroupByStore(RedisTemplate<String, List<StoreAuthMenu>> redisTemplate) {
		// TODO Auto-generated method stub
		
		ValueOperations<String, List<StoreAuthMenu>> valueOption =  redisTemplate.opsForValue();
		
		System.out.println(this.getReq().getSession().getAttribute("store_id") );
		
		List<String> rules = this.getData().parallelStream().map(StoreAuthGroup::getRules).collect(Collectors.toList());
		
		String key = MD5.MD5Encode(rules.parallelStream().map(e->e.toString()).collect(Collectors.joining(","))) + this.getReq().getSession().getAttribute("store_id").toString();
		
		
		List<StoreAuthMenu> data = valueOption.get(key);
		
		if (data != null) {
			
			return data;
		}
		data = this.getSqlTemp().getMapper(StoreAuthMenuMapper.class).getAuthMenuByUser(Arrays.asList(String.join(",", rules).split(",")));		
		
		this.getSqlTemp().clearCache();
		
		if(data == null ) {
			return data;
		}
		
		valueOption.set(key, data, 60, TimeUnit.SECONDS);
		
		
		
		return data;
	}
	
	/**
	 * 
	 */
	public Map<String, Map<String, String>> getValidateRule() {
		// TODO Auto-generated method stub
		
		
		return null;
	}


}
